<template>
    <div>
        <el-container>
            <el-header>
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="4">
                        <span style="font-size: 20px; font-weight: 1000; color: white">
                            <el-icon><HomeFilled /></el-icon>{{ $t('角色管理') }}
                        </span>
                    </el-col>
                    <el-col :span="20">
                        <div style="float: right">
                            <UiSet :type="2" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                        </div>
                    </el-col>
                </el-row>
            </el-header>
            <el-main style="padding: 0%">
                <div>
                    <el-card style="height: auto">
                        <el-form :model="findform" :inline="true" label-width="100px">
                            <el-row :gutter="10">
                                <template v-for="(item, index) in Stores.comui[componentId][0].baseProps">
                                    <el-col v-if="item.visible && item.ismore == false" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                        <el-form-item :label="I(item.label, item.labeleng)">
                                            <template #default>
                                                <div v-if="item.type === 'date'">
                                                    <el-date-picker v-model="findform[item.prop]" type="date" clearable style="width: 160px" :id="item.prop" />
                                                </div>
                                                <div v-else-if="item.prop === 'state'">
                                                    <el-select v-model="findform[item.prop]" :id="item.prop" size="default" style="width: 160px" placeholder="">
                                                        <el-option :label="$t('全部')" value="null" />
                                                        <el-option :label="$t('启用')" value="1" />
                                                        <el-option :label="$t('停用')" value="0" />
                                                    </el-select>
                                                </div>
                                                <div v-else-if="item.type === 'number'">
                                                    <el-input-number style="width: 160px" v-model="findform[item.prop]" :controls="false" :id="item.prop"></el-input-number>
                                                </div>
                                                <div v-else>
                                                    <el-input clearable v-model="findform[item.prop]" :id="item.prop" />
                                                </div>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                </template>
                                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                    <el-form-item>
                                        <el-button color="#e1d8d8" round :icon="Refresh" @click="resetForm()" id="reset">{{ $t('重置') }}</el-button>
                                        <el-button v-loading="loading" type="primary" round :icon="Search" @click="gettablelist()" id="find">{{ $t('查找') }}</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-card>
                    <el-row style="padding: 5px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><Grid /></el-icon>{{ $t('列表数据') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <el-row justify="end" :gutter="10">
                                <el-button v-loading="loading" type="primary" :icon="Plus" round @click="append()">{{ $t('新增') }}</el-button>
                                <el-popconfirm :title="$t('确定要删除选中的角色吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deletedata()" @cancel="canceldel()">
                                    <template #reference>
                                        <el-button v-loading="loading" type="danger" :icon="Delete" round style="margin-right: 10px">{{ $t('批量删除') }}</el-button>
                                    </template>
                                </el-popconfirm>
                                <excel ref="excelRef" :index="0" :Prop="uiSectionList" :comid="componentId" :title="$t('[角色管理]')" v-model:isgrant="isexcelgrant" @before-click="excelbefore" @comfirmimput="excelimputhandle"></excel>
                                <el-button v-loading="loading" color="#00b794" :icon="Document" round @click="exportEvent" style="margin-left: 10px">{{ $t('Excel导出') }} </el-button>
                                <UiSet :type="1" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-card>
                        <vxe-table :data="tablelist" border height="400" :loading="loading" :mouse-config="{ selected: true }" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }">
                            <vxe-column v-for="(column, index) in Stores.comui[componentId][0].tableProps" :field="column.prop" :title="column.label" :width="column.width" :fixed="column.fixed" :align="column.align">
                                <template #header>
                                    <div v-if="column.type === 'checkbox'">
                                        <el-checkbox v-model="Allcheck" @change="CheckAllChange" />
                                    </div>
                                    <div v-else>
                                        {{ I(column.label, column.labeleng) }}
                                    </div>
                                </template>
                                <template #default="{ row, rowIndex }">
                                    <div v-if="column.type === 'checkbox'">
                                        <el-checkbox v-model="row['checked']" />
                                    </div>
                                    <div v-else-if="column.type === 'action'">
                                        <el-button size="small" link @click="editdata(rowIndex, row)">
                                            <span style="font-size: 15px; color: #07a8d9">{{ $t('编辑') }}</span>
                                        </el-button>
                                        <span style="margin: 2px">|</span>
                                        <el-popconfirm :title="$t('确定要删除选中的角色吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deletedata(row['id'])" @cancel="canceldel()">
                                            <template #reference>
                                                <el-button v-loading="loading" type="danger" size="small" link style="margin-right: 10px">
                                                    <span style="font-size: 15px; color: red">{{ $t('删除') }}</span>
                                                </el-button>
                                            </template>
                                        </el-popconfirm>
                                    </div>
                                    <div v-else-if="column.prop === 'state'">
                                        <el-tag v-if="row.state === 1" effect="dark" round type="primary">{{ $t('启用') }}</el-tag>
                                        <el-tag v-if="row.state !== 1" effect="dark" round type="info">{{ $t('停用') }}</el-tag>
                                    </div>
                                    <div v-else>
                                        {{ row[column.prop] }}
                                    </div>
                                </template>
                            </vxe-column>
                        </vxe-table>
                        <pagemodel v-model:allcount="allcount" v-model:page="findform.page" v-model:pagecount="findform.pagecount" @pagechange="pagechange"></pagemodel>
                    </el-card>
                </div>
            </el-main>
        </el-container>
        <!-- 弹窗组件 -->
        <el-dialog v-model="dialogVisible" :title="formtitle" width="500">
            <el-form v-loading="loading" :model="formdata" label-width="130" style="max-width: 600px">
                <el-form-item :label="$t('角色ID')">
                    <el-input v-model="formdata.usrgroupid" />
                </el-form-item>
                <el-form-item :label="$t('角色名称')">
                    <el-input v-model="formdata.name" />
                </el-form-item>
                <el-form-item :label="$t('角色描述')">
                    <el-input v-model="formdata.des" />
                </el-form-item>
                <el-form-item :label="$t('启用状态')">
                    <el-switch v-model="formdata.state" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">{{ $t('取消') }}</el-button>
                    <el-button type="primary" @click="onSubmit(formdata)"> {{ $t('确定') }} </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { httpSend } from '@/utils/api';
import { getCurrentInstance, onMounted, ref, reactive, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { Refresh, Search, Plus, Document, Delete } from '@element-plus/icons-vue';
/*组件*/
import UiSet from '@/components/share/UiSet.vue';
import excel from '@/components/share/excel.vue';
import pagemodel from '@/components/share/pagemodel.vue';
//@ts-ignore
import { TableUiSection } from '@/components/share/ui-set.interface.ts';
import * as XLSX from 'xlsx'; /*excel操作*/
//@ts-ignore
import { useshareStore } from '@/store'; /*pina管理*/
import { chkgrant } from '@/globalmethods'; /*通用方法*/
const excelRef = ref(null);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
const { t } = useI18n(); //多语言

// 自定义字段配置
const componentId = 'rolesetting';
let uiSectionList: TableUiSection[] = [
    {
        baseProps: [
            { label: '角色ID', prop: 'usrgroupid', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '角色名称', prop: 'name', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '角色描述', prop: 'des', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '状态', prop: 'state', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '创建人', prop: 'tabnm', visible: true, readonly: false, type: 'string', ismore: false },
        ],
        tableProps: [
            { label: '选择', labelex: '', labeleng: '', prop: 'checked', visible: true, readonly: false, width: '80', type: 'checkbox', fixed: 'left', align: 'center' },
            { label: '角色ID', labelex: '', labeleng: '', prop: 'usrgroupid', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '角色名称', labelex: '', labeleng: '', prop: 'name', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '角色描述', labelex: '', labeleng: '', prop: 'des', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '状态', labelex: '', labeleng: '', prop: 'state', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '创建人', labelex: '', labeleng: '', prop: 'tabnm', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '创建时间', labelex: '', labeleng: '', prop: 'created_at', visible: true, readonly: false, width: '160', type: 'string', fixed: null, align: 'center' },
            { label: '修改人', labelex: '', labeleng: '', prop: 'modifier', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '修改时间', labelex: '', labeleng: '', prop: 'updated_at', visible: true, readonly: false, width: '160', type: 'date', fixed: null, align: 'center' },
            { label: '操作', labelex: '', labeleng: '', prop: 'action', visible: true, readonly: false, width: '200', type: 'action', fixed: 'right', align: 'center' },
        ],
    },
];
const loading = ref(false);
const findform = reactive({
    usrgroupid: null,
    name: null,
    des: null,
    tabnm: null,
    state: null,
    page: 1,
    pagecount: 10,
});
const Allcheck = ref(false);
const allcount = ref(0); // 总数据条数
const tablelist = ref([]); // 表格数据
const formtitle = ref('新增');
const dialogVisible = ref(false);
const formdata: any = reactive({}); // 弹窗数据
const Stores = useshareStore() as any;
Stores.setcomui([componentId, uiSectionList]);
const isexcelgrant = ref(false);
const isuigrant = ref(false);
onMounted(() => {
    //加载权限
    isexcelgrant.value = chkgrant('角色管理', 'excelimportUsrGroup');
    isuigrant.value = chkgrant('角色管理', 'customset');
    getuiset();
    gettablelist();
});

//获取配置数据
const getuiset = async () => {
    loading.value = true;
    let comdata = [];
    comdata[0] = componentId;
    comdata[1] = [];
    Object.assign(comdata[1], uiSectionList);
    const fd = new FormData();
    let data = { comid: componentId, userid: null };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getComUiSet', fd, false);
    if (res && res.code == 1) {
        if (res.data.length > 0) {
            let data = JSON.parse(res.data[0]['setjson']);
            // 如果数据依然是字符串，则需要再解析一次
            if (typeof data === 'string') {
                data = JSON.parse(data); // 第二次解析
            }
            if (data) {
                Object.assign(comdata[1], data);
            }
        }
    }
    loading.value = false;
    Stores.setcomui(comdata);
};

const gettablelist = async () => {
    if (!chkgrant('角色管理', 'getUsrGroup')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    loading.value = true;
    tablelist.value = [];
    const fd = new FormData();
    fd.append('param', JSON.stringify(findform));
    const res = await httpSend('getUsrGroup', fd, false);
    if (res && res.data && res.code == 1) {
        tablelist.value = res.data;
        allcount.value = res.count;
    }
    loading.value = false;
};

//打开新增form
const append = () => {
    if (!chkgrant('角色管理', 'saveUsrGroup')) {
        ElMessage.warning(t('您暂无新增权限,请联系管理员!'));
        return;
    }
    formtitle.value = t('新增');
    setTimeout(() => {
        for (let key in formdata) {
            if (formdata.hasOwnProperty(key)) {
                formdata[key] = null;
            }
        }
        formdata.state = 1;
        dialogVisible.value = true;
    }, 10);
};
//打开编辑
const editdata = (index: any, data: any) => {
    if (!chkgrant('角色管理', 'saveUsrGroup')) {
        ElMessage.warning(t('您暂无编辑权限,请联系管理员!'));
        return;
    }
    formtitle.value = t('修改');
    formdata.id = data.id;
    formdata.usrgroupid = data.usrgroupid;
    formdata.name = data.name;
    formdata.des = data.des;
    formdata.state = data.state;
    dialogVisible.value = true;
};

//接收excel子组件传过来的数据并进行处理
const excelimputhandle = (data, iscover) => {
    let param = {
        iscover: iscover,
        data: data,
    };
    excelimport(param);
    excelRef.value?.closeform();
};
//excel导入
const excelimport = async (data) => {
    loading.value = true;
    const fd = new FormData();
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('excelimportUsrGroup', fd);
    if (res.code == 1) {
        excelRef.value?.closeform();
        gettablelist();
    }
    loading.value = false;
};
//表头全选/取消
const CheckAllChange = (val: boolean) => {
    tablelist.value.forEach((v) => {
        v.checked = val;
    });
    tablelist.value = [...tablelist.value];
};
//重置
const resetForm = () => {
    for (let key in findform) {
        if (findform.hasOwnProperty(key)) {
            findform[key] = null;
        }
    }
};
//删除勾选
const deletedata = async (id = null) => {
    if (!chkgrant('角色管理', 'deleteUsrGroup')) {
        ElMessage.warning(t('您暂无删除权限,请联系管理员!'));
        return;
    }
    let idstr = null;
    if (id) {
        idstr = id;
    } else {
        idstr = tablelist.value
            .filter((v) => v.checked)
            .map((item) => item.id)
            .join(',');
    }
    if (!idstr) {
        ElMessage.warning('请先选择需要删除的信息!');
        return;
    }
    loading.value = true;
    const fd = new FormData();
    fd.append('param', JSON.stringify({ id: idstr }));
    const res = await httpSend('deleteUsrGroup', fd);
    if (res.code == 1) {
        gettablelist();
    }
    loading.value = false;
};

//保存
const onSubmit = async (subdata) => {
    if (!chkgrant('角色管理', 'saveUsrGroup')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    const fd = new FormData();
    fd.append('param', JSON.stringify(subdata));
    loading.value = true;
    try {
        const res = await httpSend('saveUsrGroup', fd);
        if (res.code === 1) {
            dialogVisible.value = false;
            gettablelist();
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};

//导出
const exportEvent = () => {
    if (!chkgrant('角色管理', 'excelout')) {
        ElMessage.warning(t('您暂无导出权限,请联系管理员!'));
        return;
    }
    const formattedData = tablelist.value.map((row) => {
        // 创建一个新的对象
        const newRow = {};
        Stores.comui[componentId][0].tableProps.forEach((v) => {
            if (v.visible && v.prop != 'action' && v.prop != 'checked') {
                newRow[v.label] = !!row[v.prop] ? row[v.prop] : '';
            }
        });
        return newRow; // 返回新创建的对象
    });
    // 使用自定义标题和数据生成工作表
    const ws = XLSX.utils.json_to_sheet(formattedData); // { header }
    // 创建一个新的工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 使用文件名导出 Excel 文件
    XLSX.writeFile(wb, t('角色管理导出') + '.xlsx');
};
//自定义配置权限判断
const uisetbefore = () => {
    if (!isuigrant.value) {
        ElMessage.warning(t('您暂无配置权限,请联系管理员!'));
        return;
    }
};
//excel导入前权限判断
const excelbefore = () => {
    if (!isexcelgrant.value) {
        ElMessage.warning(t('您暂无导入权限,请联系管理员!'));
        return;
    }
};
//页数变化重新查询
const pagechange=(e)=>{
    gettablelist();
}
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>
<style scoped>
:deep(.el-header) {
    --el-header-padding: 0 20px;
    --el-header-height: 60px;
    box-sizing: border-box;
    flex-shrink: 0;
    height: auto;
    padding: 0;
}
:deep(.el-card__body) {
    padding: 5px !important;
    color: #000000;
}
</style>
